package com.messi.languagehelper.db;

import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.messi.languagehelper.NoteBean;
import com.messi.languagehelper.util.ToastUtil;

public class DataBaseUtil {

	private DBOpenHelper mDbHelper;

	public DataBaseUtil(Context mContext) {
		mDbHelper = new DBOpenHelper(mContext);
	}

	public long insert(NoteBean bean) {
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(LHContract.FeedEntry.COLUMN_NAME_ENGLISH, bean.getEnglish());
		values.put(LHContract.FeedEntry.COLUMN_NAME_CHINESE, bean.getChinese());
		long newRowId = db.insert(LHContract.FeedEntry.TABLE_NAME,
				LHContract.FeedEntry.COLUMN_NAME_NULLABLE, values);
		return newRowId;
	}

	public List<NoteBean> getDataList(int offset, int maxResult) {
		List<NoteBean> noteBeans = new ArrayList<NoteBean>();
		Cursor cursor = null;
		try {
			SQLiteDatabase db = mDbHelper.getWritableDatabase();
			cursor = db.rawQuery(
					"select * from record order by recordid desc limit ?,? ",
					new String[] { String.valueOf(offset),
							String.valueOf(maxResult) });

			while (cursor.moveToNext()) {
				int recordid = cursor.getInt(cursor.getColumnIndex("recordid"));
				String english = cursor.getString(cursor
						.getColumnIndex("english"));
				String chinese = cursor.getString(cursor
						.getColumnIndex("chinese"));
				noteBeans.add(new NoteBean(recordid, english, chinese));
			}
		} catch (Exception e) {
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return noteBeans;
	}

	public void dele(Integer id) {
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		db.execSQL("delete from record where recordid=?", new Object[] { id });
	}

	public long getCount() {
		Cursor cursor = null;
		long count = 0;
		try {
			SQLiteDatabase db = mDbHelper.getWritableDatabase();
			cursor = db.rawQuery("select count(*) from record", null);
			cursor.moveToFirst();
			count = cursor.getLong(0);
		} catch (Exception e) {
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return count;
	}
	
	public void close(){
		if(mDbHelper != null){
			mDbHelper.close();
		}
	}

}
